package cn.xxm.dongbao.user.secure.dos;

import javax.servlet.http.HttpServletRequest;

public class DosStatisticsProcess {
    private DosConfig config = null;
    /**
     * Default statistics repository is HttpSession Dos
     */
    private DosStatisticsRepository repository;

    /**
     * Construct to build repository
     * @param repository Dos statistics repository
     * @param config Dos configuration
     */
    public DosStatisticsProcess(DosStatisticsRepository repository, DosConfig config) {
        this.repository = repository;
        this.config = config;
    }

    /**
     * Validate request has token or not.
     * @param request HttpServletRequest
     * @throws DosStatisticsException if token bucket hasn't token
     */
    public void doStatistics(HttpServletRequest request) throws DosStatisticsException {
        TokenBucket bucket = repository.getStatistics(request, config);
        if (!bucket.hasToken()) {
            throw new DosStatisticsException("Request rate too high.");
        }
    }
}